%Goal: mortgage market equilibrium

%INPUTS:
%alpha: household price sensitivity
%F: total mortgage face value
%Nb: number of local banks
%No: number of non-local banks
%Nn: number of shadow banks
%qn: shadow bank mortgage quality 
%qb: bank mortgage quality
%psi: bank funding cost
%rhon: common component of shadow bank funding cost
%eta: warehouse duration
%sigma_xi: volatility of shadow bank idiosyncratic taste shock
%co: non-local bank marginal cost of warehouse lending
%cb: local bank marginal cost of warehouse lending
%shadow bank idiosyncratic taste shock






function [rno, sno, rnb,snb] = Solve_sb_mortgage_inside(alpha,Nb,Nn,No,qn,qb,psi,rhon,t,eta,rhob,rhoo,sow,sbw,cb,rb)
%% set up the solution to the model

%%% household preference shock grid and transition matrix 
MaxIterations=10000;
tol = 10^(-9);
rnb_initial = 1.87;
rnb = [];
diff = 1000;
iter = 0;

while diff>tol && iter<=MaxIterations  
        iter = iter+1;
        [rno,sno] = Solve_nonlocal_financed(alpha,Nb,Nn,No,qn,qb,psi,rhon,t,eta,rhob,rhoo,sow,sbw,cb,rb,rnb_initial);
        snb =  exp(-alpha*rnb_initial+qn)/(Nb*exp(-alpha*rb+qb)+Nn*sow*No*exp(-alpha*rno+qn)+Nn*sbw*Nb*exp(-alpha*rnb_initial+qn));
        rnb = rhon+(eta/t)*(rhob-rhon)+1/(alpha*(1-snb));
        diff = abs(rnb-rnb_initial);
        rnb_initial = rnb;
  

end 
end


